<?php

namespace App\Admin\Models;

use Illuminate\Support\Facades\DB;
use App\Admin\Traits\ModelHelpers;
use DateTimeInterface;
use Illuminate\Support\Facades\Schema;

class Model extends \Illuminate\Database\Eloquent\Model
{
    use ModelHelpers;

    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format('Y-m-d H:i:s');
    }

    /**
     * 批量新增
     * @param array $data
     * @return bool $rs
     */
    public function addAll(Array $data)
    {
        $rs = DB::table($this->getTable())->insert($data);
        return $rs;
    }

    public function add($data){
        if ($this->fill($data)->save()) {
            return $this->find(DB::getPdo()->lastInsertId());
        } else {
            return false;
        }
    }

    /**
     * 批量更新
     * @param array $data
     * @return bool $rs
     */
    public function updateBatch(Array $multipleData = [])
    {
        $tableColumn = Schema::getColumnListing($this->getTable());
        try {
            if (empty($multipleData)) {
                throw new \Exception("数据不能为空");
            }
            $tableName = $this->getTable(); // 表名
            $firstRow = current($multipleData);
            $dataColumn = array_keys($firstRow);
            // 默认以id为条件更新，如果没有ID则以第一个字段为条件
            $referenceColumn = isset($firstRow['id']) ? 'id' : current($dataColumn);
            unset($dataColumn[0]);
            // 拼接sql语句
            $updateColumn = array_intersect($dataColumn, $tableColumn);
            $updateSql = "UPDATE " . $tableName . " SET ";
            $sets  = [];
            $bindings = [];
            foreach ($updateColumn as $uColumn) {
                $setSql = "`" . $uColumn . "` = CASE ";
                foreach ($multipleData as $data) {
                    $setSql .= "WHEN `" . $referenceColumn . "` = ? THEN ? ";
                    $bindings[] = $data[$referenceColumn];
                    $bindings[] = $data[$uColumn];
                }
                $setSql .= "ELSE `" . $uColumn . "` END ";
                $sets[] = $setSql;
            }
            $updateSql .= implode(', ', $sets);
            $whereIn = collect($multipleData)->pluck($referenceColumn)->values()->all();
            $bindings = array_merge($bindings, $whereIn);
            $whereIn = rtrim(str_repeat('?,', count($whereIn)), ',');
            $updateSql = rtrim($updateSql, ", ") . " WHERE `" . $referenceColumn . "` IN (" . $whereIn . ")";
            // 传入预处理sql语句和对应绑定数据
            return DB::update($updateSql, $bindings);
        } catch (\Exception $e) {
            return false;
        }
    }

    public static function validationRuleMap(){
        $locale = config('app.locale');
        $sourcePath = base_path('vendor/caouecs/laravel-lang/src');
        $path = $sourcePath.'/'.trim($locale).'/validation.php';
        $rules = file_exists($path)
            ? include $path
            : [];
        // 删除不需要的验证规则
        unset($rules['uploaded']);
        if ($rules) {
            $rules = array_slice($rules, 0, -2);
            $validationRules = [];
            $i = 0;
            foreach ($rules as $key => $value) {
                $params = [];
                $description = is_string($value) ? $value : current($value);
                preg_match_all("/\:.*?[\s|\。]/u", $description, $matchParams);
                foreach ($matchParams[0] as $matchParam) {
                    $matchParam = str_replace(' ','',$matchParam);
                    $matchParam = str_replace('。','',$matchParam);
                    $matchParam = str_replace(':','',$matchParam);
                    if ($matchParam!='attribute') {
                        if (strstr($description, $matchParam)) {
                            array_push($params, [
                                'key'=>$matchParam,
                                'value'=>null
                            ]);
                        }
                    }
                }
                array_push($validationRules, [
                    'key'=>$key,
                    'description'=>$description,
                    'params'=>$params,
                ]);
            }
            $rules = $validationRules;
        } 
        array_push($rules, [
            'key'=>'nullable',
            'description'=>':attribute 可以为空。',
            'params'=>[]
        ]);
        return $rules;
    }
}
